<template>
  <div class="profile-edit">
    <van-nav-bar title="编辑个人资料" left-arrow @click-left="handleBack" @click-right="saveProfile">
      <template #right>
        <span class="save-btn" :class="{ 'save-btn-disabled': saving }">
          {{ saving ? '保存中...' : '保存' }}
        </span>
      </template>
    </van-nav-bar>

    <div class="form-container">
      <van-form @submit.prevent="saveProfile">
        <van-cell-group inset>
          <!-- 头像 -->
          <van-field name="avatar" label="头像" readonly>
            <template #input>
              <div class="avatar-upload" @click="openImagePicker">
                <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar-preview" />
                <div v-else class="avatar-placeholder">
                  <van-icon name="photograph" size="24" />
                  <span class="upload-text">点击上传</span>
                </div>
                <input type="file" ref="fileInputRef" accept="image/*" style="display: none"
                  @change="handleFileChange" />
              </div>
            </template>
          </van-field>

          <!-- 昵称 -->
          <van-field v-model="userForm.nickname" name="nickname" label="昵称" placeholder="请输入昵称" :rules="[
            { required: true, message: '请输入昵称' },
            { min: 2, max: 20, message: '昵称长度应在2-20个字符之间' }
          ]" maxlength="20" show-word-limit />

          <!-- 邮箱 -->
          <van-field v-model="userForm.email" name="email" label="邮箱" placeholder="请输入邮箱" :rules="[
            { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入有效的邮箱地址' }
          ]" />

          <!-- 性别 -->
          <van-field v-model="userForm.gender" is-link readonly name="gender" label="性别" placeholder="请选择性别"
            @click="showGenderPicker = true" />
          <van-popup v-model:show="showGenderPicker" position="bottom">
            <van-picker :columns="genderOptions" @confirm="onGenderConfirm" @cancel="showGenderPicker = false"
              show-toolbar title="选择性别" />
          </van-popup>

          <!-- 个人简介 -->
          <van-field v-model="userForm.bio" name="bio" label="个人简介" type="textarea" rows="3" placeholder="请输入个人简介"
            maxlength="200" show-word-limit />
        </van-cell-group>
      </van-form>
    </div>

    <!-- 头像裁剪弹窗 -->
    <van-dialog v-model:show="showCropperDialog" title="裁剪头像" show-cancel-button @confirm="confirmCrop"
      :before-close="handleCropperClose" close-on-click-overlay :showConfirmButton="!cropperLoading">
      <div class="cropper-container">
        <Cropper ref="cropperRef" :src="cropperImage" :aspect-ratio="1" :min-crop-box-width="100"
          :min-crop-box-height="100" :view-mode="1" :guides="true" :center-indicator="true" :highlight="true"
          :background="true" :auto-crop="true" :auto-crop-area="0.8" :movable="true" :rotatable="true" :scalable="true"
          :zoomable="true" />
      </div>
      <div v-if="cropperLoading" class="cropper-loading">
        <van-loading type="spinner" color="#1989fa" />
        <span>上传中...</span>
      </div>
    </van-dialog>

    <!-- 未保存确认弹窗 -->
    <van-dialog v-model:show="showUnsavedDialog" title="提示" message="您有未保存的修改，确定要离开吗？" show-cancel-button
      @confirm="confirmLeave" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, showDialog } from 'vant';
import { useUserStore } from '@/stores/user';
import { Cropper } from 'vue-advanced-cropper';
import 'vue-advanced-cropper/dist/style.css';
import { userApi } from '@/api/user';

const router = useRouter();
const userStore = useUserStore();
const fileInputRef = ref<HTMLInputElement | null>(null);
const cropperRef = ref(null);
const cropperImage = ref('');
const showCropperDialog = ref(false);
const cropperLoading = ref(false);
const saving = ref(false);
const showGenderPicker = ref(false);
const showUnsavedDialog = ref(false);
const formChanged = ref(false);

// 性别选项
const genderOptions = [
  { text: '男', value: 'male' },
  { text: '女', value: 'female' },
  { text: '保密', value: 'secret' }
];

// 性别显示文本
const genderDisplayMap = {
  male: '男',
  female: '女',
  secret: '保密'
};

// 用户表单数据
const userForm = reactive({
  nickname: '',
  avatar: '',
  email: '',
  bio: '',
  gender: '',
  avatarFile: null as File | null,
  originalData: {} as any // 用于存储原始数据，以便检测变更
});

// 初始化用户数据
onMounted(async () => {
  try {
    await userStore.getUserInfo();
    const userInfo = userStore.userInfo;

    userForm.nickname = userInfo.nickname || '';
    userForm.avatar = userInfo.avatar || '';
    userForm.email = userInfo.email || '';
    userForm.bio = userInfo.bio || '';
    userForm.gender = userInfo.gender || 'secret';

    // 保存原始数据用于比较
    userForm.originalData = {
      nickname: userForm.nickname,
      avatar: userForm.avatar,
      email: userForm.email,
      bio: userForm.bio,
      gender: userForm.gender
    };

    console.log('获取到的用户信息:', userInfo);
    console.log('初始化表单数据:', userForm);
  } catch (error) {
    console.error('获取用户信息失败', error);
    showToast('获取用户信息失败');
  }
});

// 保存个人资料
const saveProfile = async () => {
  if (saving.value) return;

  try {
    if (!userForm.nickname) {
      showToast('请输入昵称');
      return;
    }

    saving.value = true;

    const updateData = {
      nickname: userForm.nickname,
      bio: userForm.bio,
      email: userForm.email,
      gender: userForm.gender
    };

    console.log('提交的更新数据:', updateData);

    const response = await userApi.updateUserInfo(updateData);
    console.log('更新用户信息响应:', response);

    await userStore.getUserInfo(); // 刷新用户信息

    showToast('保存成功');
    router.back();
  } catch (error: any) {
    console.error('保存个人资料失败', error);
    showToast(error.response?.data?.message || '保存个人资料失败');
  } finally {
    saving.value = false;
  }
};
</script>

<style scoped lang="scss">
.profile-edit {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.form-container {
  padding: 16px 0;
}

.save-btn {
  color: #1989fa;
  font-size: 14px;
  font-weight: 500;

  &-disabled {
    color: #a0cfff;
  }
}

.avatar-upload {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: #f2f3f5;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed #dcdee0;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #969799;

  .upload-text {
    font-size: 12px;
    margin-top: 4px;
  }
}

.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cropper-container {
  height: 300px;
  background-color: #000;
  position: relative;
}

.cropper-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  z-index: 10;

  span {
    margin-top: 10px;
  }
}

:deep(.van-cell-group) {
  margin: 0 16px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(100, 101, 102, 0.08);
}

:deep(.van-field__label) {
  width: 80px;
  color: #323233;
}

:deep(.van-field__word-limit) {
  color: #969799;
  font-size: 12px;
  margin-top: 4px;
}
</style>
